from django.utils.deprecation import MiddlewareMixin
# from myadmin.models import Log
import json
import re


class Test(MiddlewareMixin):
    def process_response(self, request, response):
        query = {}
        result = ''
        code = ''
        query["path"] = request.path
        query["ip"] = self.get_client_ip(request)
        query["user_id"] = request.user.id
        query["method"] = request.method.upper()

        # 用于首页 文件上传等返回不了code的请求
        if request.path in ["/"]:
            code = "20000"
            result = "请求成功"
        else:
            try:
                data = self.get_data(response)
                code = str(data.get("code", ''))
                result = str(data.get("message", ""))
                if not result and "data" in data:
                    result = "请求成功"
                if not code.isdigit():
                    raise AttributeError
            except Exception as e:
                code = "code不规范：%s" % code
                result = str(e)

        query["code"] = code
        query["result"] = result[:1020]

        if response.status_code == 500:
            query["code"] = 500
            query["result"] = "服务器出错"
        elif response.status_code == 404:
            query["code"] = 404
            query["result"] = "页面未找到"
        elif response.status_code != 200:
            query["code"] = response.status_code
            try:
                status_text = response.status_text
            except Exception as e:
                query["result"] = result[:1020]
            else:
                query["result"] = status_text
        try:
            Log.objects.create(**query)
        except Exception as e:
            query["code"] = ""
            query["result"] = str(e)[:2000]
            Log.objects.create(**query)
        return response

    def get_client_ip(self, request):
        # 这个需要配置了Nginx才有
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[-1].strip()
        else:
            ip = request.META.get('REMOTE_ADDR')
        return ip

    def get_data(self, response):
        if response.streaming:
            return {"code": 20000, "message": "文件下载成功"}
        data = getattr(response, "content", b"{}").decode()
        try:
            return json.loads(data)
        except:
            return {"code": response.status_code, "message": "非json格式"}


